package com.zx.dsptuneup_TriMic.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.base.tools.tools.StringUtils;
import com.multilevel.treelist.Node;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zx.dsptuneup_TriMic.Adapter.TransferChildAdapter;
import com.zx.dsptuneup_TriMic.Base.BaseActivity;
import com.zx.dsptuneup_TriMic.NodeTree.MTreeRecycleAdapter;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.CVIPaperDialogUtils;
import com.zx.dsptuneup_TriMic.Tools.Constant;
import com.zx.dsptuneup_TriMic.Util.ToastUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.bean.DeviceBean;
import com.zx.dsptuneup_TriMic.bean.TreeListBean;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;
import com.zx.dsptuneup_TriMic.widget.ui.DividerItemDecoration;
import com.zx.dsptuneup_TriMic.widget.ui.EmptyView;
import com.zx.dsptuneup_TriMic.widget.ui.LoadingView;
import com.zx.dsptuneup_TriMic.widget.ui.RecyclerViewEmptySupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author cyj
 * @createDate 2021-11-15
 * @ClassName: TransferChildActivity
 * @Description: 转移子设备
 * @Version: 1.0
 */
public class TransferParentActivity extends BaseActivity implements MTreeRecycleAdapter.OnItemClickListener {
    @BindView(R.id.ic_nav)
    TextView nav_left;
    @BindView(R.id.position_tree)
    TextView position_tree;
    @BindView(R.id.inc_loading_view)
    LoadingView mILoadingView;
    @BindView(R.id.confim_control)
    TextView confim_control;

    private String deviceId = null;
    // 树状结构相关
    private PopupWindow mPop = null;
    private Drawable drawable_selected = null;
    private Drawable drawable_normal = null;
    private MTreeRecycleAdapter mAdapter;
    protected List<Node> mDatas = new ArrayList<Node>();            // 树状图数据结构
    private String currentSelPositionId = "";   // 当前选择的位置信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfor_parent);
        Intent intent = getIntent();
        deviceId = intent.getStringExtra(Constant.addDevicesID);
        initUI();
        initData();
    }

    private void initUI() {
        mILoadingView.showLoading();
        nav_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Rect bonds = new Rect(0, 0, 17,9);
        Rect bond_r = new Rect(0, 0, 8,14);
        drawable_selected = getResources().getDrawable(R.mipmap.arrow);
        drawable_selected.setBounds(bonds);

        drawable_normal = getResources().getDrawable(R.mipmap.arrow_r);
        drawable_normal.setBounds(bond_r);

        position_tree.setSelected(false);
        position_tree.setCompoundDrawables(null, null, drawable_normal, null);
        position_tree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position_tree.setSelected(!position_tree.isSelected());
                if(position_tree.isSelected()){
                    position_tree.setCompoundDrawables(null, null, drawable_selected, null);
                }else{
                    position_tree.setCompoundDrawables(null, null, drawable_normal, null);
                }
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                }else {
                    showPopupWindow(view);
                }
            }
        });
        confim_control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(StringUtils.isEmpty(currentSelPositionId)){
                    ToastUtil.makeText(TransferParentActivity.this,"未选择位置!");
                    return;
                }
                HashMap map = new HashMap();
                map.put("positionId", currentSelPositionId);
                map.put("id", deviceId);
                NetWorkManager.getInstance().getNetWorkApiService().deviceMod(map).compose(TransferParentActivity.this.<BasicResponse<String>>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<BasicResponse<String>>() {
                            @Override
                            protected void onSuccess(BasicResponse<String> response) {
                                if (response != null) {
                                    ToastUtil.makeText(TransferParentActivity.this,"转移成功!");
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            finish();
                                        }
                                    },300);
                                }
                            }

                            @Override
                            protected void onFail(BasicResponse<String> response) {
                                super.onFail(response);
                                mILoadingView.hideLoading();
                                showExitDialog();
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                super.onError(e);
                                mILoadingView.hideLoading();
                                showExitDialog();
                            }
                        });

            }
        });
    }


    private void initData() {
        // 1.获取位置信息
        NetWorkManager.getInstance().getNetWorkApiService().getTree().compose(TransferParentActivity.this.<BasicResponse<List<TreeListBean>>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<BasicResponse<List<TreeListBean>>>() {
                    @Override
                    protected void onSuccess(BasicResponse<List<TreeListBean>> response) {
                        if (response != null) {
                            mILoadingView.hideLoading();
                            List<TreeListBean> treeListBeanList = response.getData();
                            initTreeDatas(treeListBeanList);
                        }
                    }

                    @Override
                    protected void onFail(BasicResponse<List<TreeListBean>> response) {
                        super.onFail(response);
                        mILoadingView.hideLoading();
                        showExitDialog();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        super.onError(e);
                        mILoadingView.hideLoading();
                        showExitDialog();
                    }
                });
    }

    private void showExitDialog(){
        CVIPaperDialogUtils.showConfirmDialog(TransferParentActivity.this, "获取位置信息异常!", "返回", false, new CVIPaperDialogUtils.ConfirmDialogListener() {
            @Override
            public void onClickButton(boolean clickConfirm, boolean clickCancel) {
                if(clickConfirm){
                    finish();
                }
            }
        });
    }

    /**
     *  加载树形数据和设备列表
     * */
    private void initTreeDatas(List<TreeListBean> originalData) {
        if (originalData.size() < 1) {
            return;
        }
        mDatas.clear();
        if (originalData.size() == 1) {
            Node node = new Node(originalData.get(0).getId(), -1, originalData.get(0).getPositionName());
            mDatas.add(node);
        } else {
            for (int i = 0; i < originalData.size(); i++) {
                TreeListBean treeListBean = originalData.get(i);
                Node node;
                if (StringUtils.isEmpty(treeListBean.getParentId())) {
                    node = new Node(treeListBean.getId(), -1, treeListBean.getPositionName());
                } else {
                    node = new Node(treeListBean.getId(), treeListBean.getParentId(), treeListBean.getPositionName());
                }
                mDatas.add(node);
            }
        }
        if (mAdapter != null) {
            // 展开层级，暂定
            mAdapter.addDataAll(mDatas, 0);
        }
        // 默认选择最顶层
        position_tree.setText(originalData.get(0).getPositionName());
        // 加载设备列表
        String positionId = originalData.get(0).getId();
        currentSelPositionId = positionId;
    }


    // 树状item点击
    @Override
    public void onItemClicked(Node node, int position) {
        Log.e("onItemClicked","position======="+position);
        position_tree.setText(node.getName());
        // 加载设备列表
        String positionId = (String) node.getId();
        currentSelPositionId = positionId;
    }


    public void showPopupWindow(View parent){//显示下拉弹出的窗口
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        // 显示的宽度为:屏幕的宽度的一半
        View view = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
        if(mPop==null){//注意，布局文件的控件设置为fill_parent，否则此处初始化的窗口大小不会变化
            mPop = new PopupWindow();
            mPop.setContentView(view);
            mPop.setWidth((int)(windowManager.getDefaultDisplay().getWidth()*0.7));
            mPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        }
        // 收起列表
        TextView collapseTxt =  view.findViewById(R.id.collapse);
        collapseTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPop != null && mPop.isShowing()) {
                    mPop.dismiss();
                    mPop = null;
                    position_tree.setSelected(false);
                    position_tree.setCompoundDrawables(null, null, drawable_normal, null);
                }
            }
        });
        // 聚焦
        mPop.setFocusable(false);
        mPop.setOutsideTouchable(false);
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setAnimationStyle(R.style.popupwindow_animation_style);
        mPop.showAsDropDown(parent,0,0);

        RecyclerView mTree = (RecyclerView) view.findViewById(R.id.recyclerview);
        mTree.addItemDecoration(new DividerItemDecoration(TransferParentActivity.this, DividerItemDecoration.VERTICAL_LIST));
        mTree.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new MTreeRecycleAdapter(mTree, TransferParentActivity.this,mDatas, 1,R.mipmap.tree_ec,R.mipmap.tree_ex);
        mAdapter.setShowOperation(false);
        mAdapter.setOnItemClickListener(TransferParentActivity.this);
        mTree.setAdapter(mAdapter);
    }
}
